/**
 * Copyright 2020 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.dbfly.mybatis.version;

import java.sql.Timestamp;
import java.util.Date;

import com.jianggujin.dbfly.mybatis.entity.JEntity;
import com.jianggujin.dbfly.mybatis.entity.JEntityColumn;
import com.jianggujin.dbfly.util.JDBFlyException;

/**
 * 默认版本号生成器
 *
 * @author jianggujin
 */
public class JDefaultVersionGenerator implements JVersionGenerator {

    @Override
    public Object generateVersion(JEntity entity, JEntityColumn column, Object current) {
        if (current == null) {
            Class<?> javaType = column.getJavaType();
            if (int.class.equals(javaType) || Integer.class.equals(javaType) || long.class.equals(javaType)
                    || Long.class.equals(javaType)) {
                return 0;
            }
            if (Timestamp.class.equals(javaType)) {
                return new Timestamp(System.currentTimeMillis());
            }
            if (Date.class.equals(javaType)) {
                return new Date();
            }
            throw new JDBFlyException("当前版本号为空且数据类型无法自动初始化!");
        }
        if (current instanceof Integer) {
            return (Integer) current + 1;
        }
        if (current instanceof Long) {
            return (Long) current + 1L;
        }
        if (current instanceof Timestamp) {
            return new Timestamp(System.currentTimeMillis());
        }
        if (current instanceof Date) {
            return new Date();
        }
        throw new JDBFlyException("默认的 JDefaultVersionGenerator不支持数据类型[{}]的版本!", current.getClass().getCanonicalName());
    }

}
